//
//  SettingsViewController.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 9/13/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "SettingsViewController.h"
@interface SettingsViewController()<DBRestClientDelegate>
{
    
}
@end

@implementation SettingsViewController
@synthesize lockSwitch;
@synthesize activityIndicator;
@synthesize testImageView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Settings", @"Settings");
        self.tabBarItem.image = [UIImage imageNamed:@"icon-setting.png"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated {
   // if([])
    [super viewWillAppear:animated];
    [self updateSwitch];
    
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    [lockSwitch setOn:delegate.currentWallet.w_isLocked.boolValue];
    
    if([[DBSession sharedSession]isLinked]) {
        [self didLoadPhotos];
    }
}

- (void)viewDidUnload
{
    mySwitcher = nil;
    [self setActivityIndicator:nil];
    [self setTestImageView:nil];
    [self setLockSwitch:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)switchValueChanged:(id)sender {
    if(![[DBSession sharedSession]isLinked]) {
        [[DBSession sharedSession]linkFromController:self];
    } else {
        [[DBSession sharedSession] unlinkAll];
        [[[UIAlertView alloc]
           initWithTitle:@"Account Unlinked!" message:@"Your dropbox account has been unlinked"
           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]
         show];
    }
}

- (IBAction)lockSwitchValueChanged:(id)sender {
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.currentWallet.w_isLocked = [NSNumber numberWithBool:lockSwitch.isOn];
    [DataBaseAccess saveData];
}

- (IBAction)backButtonPressed:(id)sender {
    folyAppDelegate *myDelegate =   (folyAppDelegate *)[[UIApplication sharedApplication]delegate];
    [myDelegate.navigationController popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadTableView" object:nil];
}

- (IBAction)backupDatabase:(id)sender {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    
    NSString *resourcePath = [documentPath stringByAppendingPathComponent:@"Wallets_Manager.sqlite"];
    NSString *destinationPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"BackupWallets_Manager.sqlite"];
    if([fileManager fileExistsAtPath:destinationPath] == NO){
//        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"Wallets_Manager" ofType:@"sqlite"];
        [fileManager copyItemAtPath:resourcePath toPath:destinationPath error:&error];
    } else {
        [fileManager removeItemAtPath:destinationPath error:&error];
        [fileManager copyItemAtPath:resourcePath toPath:destinationPath error:&error];
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Backup Successfully" message:@"File Backup : Wallet_Manager.sqlite" delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil];
    [alertView show];
}

- (IBAction)restoreDatabase:(id)sender {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
    NSString *documentPath = [paths objectAtIndex:0];
    
    NSString *resourcePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"BackupWallets_Manager.sqlite"];
    NSString *destinationPath = [documentPath stringByAppendingPathComponent:@"Wallets_Manager.sqlite"];
    
    //if([fileManager fileExistsAtPath:destinationPath] == YES) {
        [fileManager removeItemAtPath:destinationPath error:&error];
        [fileManager copyItemAtPath:resourcePath toPath:destinationPath error:&error];
    //}
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Restore Successfully" message:@"File Restore : Wallet_Manager.sqlite" delegate:self cancelButtonTitle:@"OK"otherButtonTitles: nil];
    [alertView show];
}

- (IBAction)languagePressed:(id)sender {
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"" message:@"Coming soon in next version" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alertView show];
}

- (IBAction)aboutButtonPressed:(id)sender {
}

-(void)updateSwitch {
    [mySwitcher setOn:[[DBSession sharedSession]isLinked]];
}

#pragma mark --------------Private Method------------
- (void)didLoadPhotos {
    [self setWorking:YES];
    
    NSString *photosRoot = nil;
    if ([DBSession sharedSession].root == kDBRootDropbox) {
        photosRoot = @"/Photos";
    } else {
        photosRoot = @"/";
    }
    
    NSString *localPath = [[NSBundle mainBundle] pathForResource:@"navigationbar" ofType:@"jpg"];
    NSString *filename = @"navigationbar.jpg";
    NSString *destDir = @"/";
    
    [[self restClient] uploadFile:filename toPath:destDir
                    withParentRev:nil fromPath:localPath];
    
    [self.restClient loadMetadata:photosRoot withHash:photosHash];
    
    
}

-(void)loadRandomPhoto {
    
    if ([photoPaths count] == 0) {
        
        NSString *msg = nil;
        if ([DBSession sharedSession].root == kDBRootDropbox) {
            msg = @"Put .jpg photos in your Photos folder to use DBRoulette!";
        } else {
            msg = @"Put .jpg photos in your app's App folder to use DBRoulette!";
        }
        
        [[[UIAlertView alloc]
           initWithTitle:@"No Photos!" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]show];
        
        [self setWorking:NO];
    } else {
        NSString* photoPath;
        if ([photoPaths count] == 1) {
            photoPath = [photoPaths objectAtIndex:0];
            if ([photoPath isEqual:currentPhotoPath]) {
                [[[UIAlertView alloc]
                   initWithTitle:@"No More Photos" message:@"You only have one photo to display."
                   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]show];
                
                [self setWorking:NO];
                return;
            }
        } else {
            // Find a random photo that is not the current photo
            do {
                srandom(time(NULL));
                NSInteger index =  random() % [photoPaths count];
                photoPath = [photoPaths objectAtIndex:index];
            } while ([photoPath isEqual:currentPhotoPath]);
        }
        
        currentPhotoPath = photoPath ;
        
        [self.restClient loadThumbnail:currentPhotoPath ofSize:@"iphone_bestfit" intoPath:[self photoPath]];
    }
}

- (NSString*)photoPath {
    return [NSTemporaryDirectory() stringByAppendingPathComponent:@"photo.jpg"];
}

- (void)setWorking:(BOOL)isWorking {
    if (working == isWorking) return;
    working = isWorking;
    
    if (working) {
        [activityIndicator startAnimating];
    } else {
        [activityIndicator stopAnimating];
    }
}

- (void)displayError {
    [[[UIAlertView alloc]
       initWithTitle:@"Error Loading Photo" message:@"There was an error loading your photo."
       delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]show];
}

#pragma mark ----------------DropBox Delegate----------------

- (DBRestClient*)restClient {
    if (restClient == nil) {
        restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
        restClient.delegate = self;
    }
    return restClient;
}

- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata {
   
    photosHash = metadata.hash;
    
    NSArray* validExtensions = [NSArray arrayWithObjects:@"jpg", @"jpeg",@"png", nil];
    NSMutableArray* newPhotoPaths = [NSMutableArray new];
    for (DBMetadata* child in metadata.contents) {
        NSString* extension = [[child.path pathExtension] lowercaseString];
        if (!child.isDirectory && [validExtensions indexOfObject:extension] != NSNotFound) {
            [newPhotoPaths addObject:child.path];
        }
    }
    photoPaths = newPhotoPaths;
    [self loadRandomPhoto];
}

- (void)restClient:(DBRestClient*)client metadataUnchangedAtPath:(NSString*)path {
    [self loadRandomPhoto];
}

- (void)restClient:(DBRestClient*)client loadMetadataFailedWithError:(NSError*)error {
    NSLog(@"restClient:loadMetadataFailedWithError: %@", [error localizedDescription]);
    [self displayError];
    [self setWorking:NO];
}


-(void)restClient:(DBRestClient *)client loadedThumbnail:(NSString *)destPath {
    testImageView.image = [UIImage imageWithContentsOfFile:destPath];
}

- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath
              from:(NSString*)srcPath metadata:(DBMetadata*)metadata {
    
    NSLog(@"File uploaded successfully to path: %@", metadata.path);
}

- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error {
    NSLog(@"File upload failed with error - %@", error);
}
@end
